package com.wgl.va.recognizer.baidu;

import java.io.IOException;
import java.util.HashMap;

import org.json.JSONObject;

import com.baidu.aip.error.AipError;
import com.baidu.aip.http.AipRequest;
import com.baidu.aip.http.EBodyFormat;
import com.baidu.aip.speech.AipSpeech;
import com.baidu.aip.util.AipClientConst;
import com.baidu.aip.util.Base64Util;
import com.baidu.aip.util.SignUtil;
import com.baidu.aip.util.Util;
import com.wgl.va.common.Tool;

public class AipSpeechExt extends AipSpeech {

	public AipSpeechExt(String appId, String apiKey, String secretKey) {
		super(appId, apiKey, secretKey);
		// TODO Auto-generated constructor stub
	}

	public JSONObject asr(byte[] data, String format, int rate, String uri, HashMap<String, Object> options) {
		AipRequest request = new AipRequest();

		preOperation(request);
		if (this.isBceKey.get()) {
			return Util.getGeneralError(AipClientConst.OPENAPI_NO_ACCESS_ERROR_CODE.intValue(),
					"No permission to access data");
		}

		String base64Content = Base64Util.encode(data);
		request.addBody("speech", base64Content);
		request.addBody("format", format);
		request.addBody("rate", Integer.valueOf(rate));
		request.addBody("channel", Integer.valueOf(1));
		String cuid = SignUtil.md5(this.accessToken, "UTF-8");
		request.addBody("cuid", cuid);
		request.addBody("token", this.accessToken);
		request.addBody("len", Integer.valueOf(data.length));
		if (options != null) {
			request.addBody(options);
		}
		if (Tool.validStr(uri)) {
			request.setUri(uri);
		} else {
			request.setUri("http://vop.baidu.com/server_api");
		}
		request.setBodyFormat(EBodyFormat.RAW_JSON);
		request.addHeader("Content-Type", "application/json");

		return requestServer(request);
	}

	public JSONObject asrWav(String path, int rate, String uri) {
		try {
			byte[] imgData = Util.readFileByBytes(path);
			return asr(imgData, "wav", rate, uri, null);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return AipError.IMAGE_READ_ERROR.toJsonResult();
	}

}
